import random
from django.shortcuts import render
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from utils.ytx_sdk.sendSMS import CCP
from . import constants
from celery_tasks.sms.tasks import send_sms_code


# Create your views here.
class SMS_Code_View(APIView):
    def get(self, request, mobile):
        """发送短信验证码接口"""
        # 获取redis数据库连接
        redis_cli = get_redis_connection('sms_code')
        # 验证六十秒内是否向指定用户发送过短信,是:报错,抛出异常
        if redis_cli.get('sms_flag_' + mobile):
            raise serializers.ValidationError('发送验证码过于频繁')

        # 否:逻辑处理
        # 1.生成随机验证码
        code = random.randint(100000, 999999)

        # 2.将验证码和已发送标记并保存到redis数据库中
        # redis_cli.setex('sms_code_' + mobile, 300, sms_code)
        # redis_cli.setex('sms_flag_' + mobile, 60, 1)
        """利用管道进行代码优化"""
        redis_pipeline = redis_cli.pipeline()
        redis_pipeline.setex('sms_code_' + mobile, constants.SMS_CODE_EXPIRES, code)
        redis_pipeline.setex('sms_flag_' + mobile, constants.SMS_FLAG_EXPIRES, 1)
        redis_pipeline.execute()
        # 3.云通讯发送短信
        # print(redis_cli.get("sms_code_"+mobile))
        # CCP.sendTemplateSMS(mobile, code, constants.SMS_FLAG_EXPIRES/60,1)

        # 调用celery执行耗时函数
        send_sms_code.delay(mobile, code, constants.SMS_FLAG_EXPIRES/60,1)

        # 响应
        return Response({'message': 'OK'})
